package dataBase;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

import castleContent.Users;
import controler.RegisterServlet;

public class DataBase {

	private static final String USERS_TABLE = "USERS";
	private static Connection dbCon;
	private static int gold;
	private static int food;
	private static int army_capacity;
	private static int army;

	public static void initializeDataBase() {
		try {
			dbCon = establishDBConnection();
			String username = Users.users.get(RegisterServlet.getUsername()).getName();
			String password = Users.users.get(RegisterServlet.getUsername()).getPassword();
			int age = Integer.parseInt(Users.users.get(RegisterServlet.getUsername()).getAge());
			String race = Users.users.get(RegisterServlet.getUsername()).getRace();
			String city = Users.users.get(RegisterServlet.getUsername()).getCity();

			List<String> tableList = GetColumnsAsListsFromDB.getExistingTableNamesAsList(dbCon);

			if (!tableList.contains(USERS_TABLE)) {
				CreateDBTables.createAllTables(dbCon);
				FillDBTables.fillUserCityTable(dbCon);
				FillDBTables.fillUserRaceTable(dbCon);
			}

			int raceNumber = ForeignKeyCheck.raceNumberCheck(race);
			int cityNumber = ForeignKeyCheck.cityNumberCheck(city);

		    FillAllDBTables(username, password, age, raceNumber, cityNumber);
			
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		} 
	}

	private static void FillAllDBTables(String username, String password,
			int age, int raceNumber, int cityNumber) throws SQLException {
		FillDBTables.insertIntoUsersTable(dbCon, username, password, age,
				raceNumber, cityNumber, gold, food, army_capacity, army);
		FillDBTables.insertIntohp_ad_levelsTable(dbCon, username);
		FillDBTables.insertIntoBuildingsTable(dbCon);
	}

	public static Connection establishDBConnection()
			throws ClassNotFoundException, SQLException {

		Class.forName("oracle.jdbc.driver.OracleDriver");

		dbCon = DriverManager.getConnection(
				"jdbc:oracle:thin:@localhost:1521/xe", "Admin", "!voOo3");
		return dbCon;
	}

	public static Connection getDbCon() {
		return dbCon;
	}
}
